import React, { useMemo, useState } from "react";
import { withRouter } from "react-router-dom";
import styles from "./index.module.scss";
import Buttons from "../../components/choiceButtons";
import { pageIndex, pages } from "../../common/routerConfig";
import { formatNum } from "../../utils/format";

const NULL_ERR = "请选择一个答案";

// 考试页面
const Index = (props) => {
  const { history } = props;
  const { query } = props.location;
  let ques = {};
  if (!query || !(ques = query["m_quesAndanswers"])) {
    alert("未获取到题目");
    history.push(pages[pageIndex.home].path);
  }

  // 正确的题目数量
  const [credit, setCredit] = useState(0);

  // 用户当前选择的答案
  const [curChoice, setCurChoice] = useState("");

  // 当前访问第几个题目
  const [index, setIndex] = useState(0);

  // 没有做出选择时的提示
  const [hint, setHint] = useState("");

  // 对象的key值数组
  const keys = useMemo(() => Object.keys(ques), [ques]);

  // 题目总数
  const qCount = useMemo(() => keys.length, [keys]);

  // 当前正在做的题目
  const curQue = useMemo(() => keys[index], [index, keys]);

  // 当前做的题目的正确答案
  const curAns = useMemo(() => formatNum(ques ? ques[curQue] : 0), [curQue]);

  // 所有选项
  const choices = useMemo(() => {
    const choices = [
      formatNum(curAns),
      formatNum(curAns - -Math.random() * 2),
      formatNum(curAns - Math.random() * 2),
      Math.random() < 0.5
        ? formatNum(curAns - Math.random() * 4)
        : formatNum(curAns - -Math.random() * 4),
    ];
    for (let i = 1; i < choices.length; i++) {
      const r = Math.floor(Math.random() * (i + 1));
      [choices[i], choices[r]] = [choices[r], choices[i]];
    }
    return choices;
  }, [curAns]);

  // 处理跳转按钮的点击
  // 最后一题则计算总成绩，跳转
  const handleClick = () => {
    if (curChoice === "") {
      setHint((h) => NULL_ERR);
    } else if (index < qCount - 1) {
      if (curChoice === curAns) setCredit((p) => p + 1);
      setIndex((i) => i + 1);
      setCurChoice((p) => "");
    } else if (index === qCount - 1) {
      let final = credit;
      if (curChoice === curAns) {
        final = credit + 1;
      }
      const result = formatNum((final / qCount) * 100);
      history.push({
        pathname: pages[pageIndex.result].path,
        query: {
          result: result,
        },
      });
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        {index + 1}) {curQue}
        <label className={styles.curChoice}>
          {curChoice ? curChoice : "?"}
        </label>
      </div>
      <Buttons
        choices={choices}
        setCurChoice={setCurChoice}
        setHint={setHint}
      />
      <div className={styles.hint}>{hint}</div>
      <div className={styles.action}>
        <div className={styles.btn} onClick={handleClick}>
          {index === qCount - 1 ? "finish" : "next"}
        </div>
      </div>
    </div>
  );
};

export default withRouter(Index);
